(function($){
    $.fn.serializeJson=function(){
        var serializeObj={};
        var array=this.serializeArray();
        // var str=this.serialize();
        $(array).each(function(){
            if(serializeObj[this.name]){
                if($.isArray(serializeObj[this.name])){
                    serializeObj[this.name].push(this.value);
                }else{
                    serializeObj[this.name]=[serializeObj[this.name],this.value];
                }
            }else{
                serializeObj[this.name]=this.value;
            }
        });
        return serializeObj;
    };
})(jQuery);

$(document).ready(function(){
    var timeLineFn = baidu.template('timeLineTmpl');
    var activityFn = baidu.template('activityTmpl');
    var radioFn = baidu.template('radioTmpl');

    var eidtorDom = $('#activityContentModle');
    eidtorDom.hide();
    var ueditor = UE.getEditor('ueditor', {wordCount: true});
    var editTitle = $('<input type="text" name="title" placeholder="标题" '+
        'class="col-xs-9" style="margin-left: 10px;margin-top: 2px;" />');
    $('body').on('click', '.add-activity', function() {
        $(this).parents('.timeline-container').append(activityFn({}));
    });

    $('body').on('click', '.edit-activity', function(e) {
        e.preventDefault();
        var activityDiv =  $(this).parents('div.transparent');
        if($('.confirm-activity:visible').length>0){//确认按钮显示出来说明已经有活动处于编辑状态
            var previousActivityDiv = editTitle.parents('div.transparent');
            previousActivityDiv.find('.confirm-activity').hide();
            previousActivityDiv.find('.edit-activity').show();
            previousActivityDiv.find('.activity-title').show();
            previousActivityDiv.find('.activity-content').show();
        }
        activityDiv.find('.confirm-activity').show();
        activityDiv.find('.edit-activity').hide();
        activityDiv.find('.activity-content').hide();
        activityDiv.find('.activity-title').hide();

        editTitle.val(activityDiv.find('.activity-title').text());
        editTitle.show();
        activityDiv.find('.activity-title-h5').append(editTitle);
        setTimeout(function () {//解决百度 editor setContent()方法无效的问题
            ueditor.setContent(activityDiv.find('.activity-content').html(),false);
        },500);
        activityDiv.find('.widget-body').append(eidtorDom);
        eidtorDom.show();
    });
    $('body').on('click', '.confirm-activity', function(e) {
        e.preventDefault();
        var activityDiv =  $(this).parents('div.transparent');
        activityDiv.find('.confirm-activity').hide();
        activityDiv.find('.edit-activity').show();

        var title = editTitle.val();
        var content = ueditor.getContent();
        activityDiv.find('.activity-title').text(title);
        activityDiv.find('.activity-title').show();
        activityDiv.find('.activity-content').html(content);
        activityDiv.find('.activity-content').show();
        editTitle.hide();
        eidtorDom.hide();

    });
    $('body').on('click', '.delete-activity', function(e) {
        e.preventDefault();
        $(this).parents('div.timeline-items').remove();
    });
    $('body').on('click', '.add-day', function(e) {
        e.preventDefault();
        $('#timeline_content .delete-day').hide();
        $('#timeline_content').append(timeLineFn({dayNo:$('.timeline-container').length+1}));
    });
    $('body').on('click', '.delete-day', function(e) {
        e.preventDefault();
        var delDay = $(this).parents('div.timeline-container');
        bootbox.confirm({
            title:'请确认',
            message: "确定要删除该日行程？",
            buttons: {
                confirm: {
                    label: '确定',
                    className: 'btn-success'
                },
                cancel: {
                    label: '取消',
                    className: 'btn-default'
                }
            },
            callback: function (result) {
                if(result){
                    delDay.remove();
                    $('#timeline_content .delete-day:last').show();
                }
            }
        });

    });

    $('#submitBtn').click(function (e) {
        e.preventDefault();
        var data=$("#routeForm").serializeJson();//表单序列化
        data.trip = JSON.stringify(initParam());
        jQuery.ajax({
            dataType : 'json',
            type:'post',
            url : $('#routeForm').attr('action'),
            data :data,
            success : function(result) {
                if(result.code=='200'){
                    bootbox.confirm({
                        title:'提示信息',
                        message: result.message+'是否继续添加？',
                        buttons: {
                            confirm: {
                                label: '确定',
                                className: 'btn-success'
                            },
                            cancel: {
                                label: '取消',
                                className: 'btn-default'
                            }
                        },
                        callback: function (result) {
                            if(result){
                                if($('input[name="id"]').val()==""){
                                    $('#routeForm')[0].reset();
                                    $('#timeline_content').empty();
                                }else{
                                    // var url = $('#addUrl').val();
                                    window.location.href="/tour/route/input.do?taId="+$('#travelAgencyId').val();
                                }
                            }else{
                                window.location.href="/tour/route/list.do?taId="+$('#travelAgencyId').val();
                            }
                        }
                    });
                }else{
                    bootbox.alert(result.message);
                }
            },
            error:function () {
                bootbox.alert('请求失败！');
            }
        });
    });
    $('#resetBtn').click(function(e) {
        $('#routeForm')[0].reset();
    });
    var dataPickerOption ={
        // todayBtn : "linked",
        autoclose : true,
        todayHighlight : true,
        format:'yyyy-mm-dd',
        language : 'zh-CN'
    }
    $('#startTime').datepicker(dataPickerOption).on('changeDate',function(e){
        var startTime = e.date;
        $('#endTime').datepicker('setStartDate',startTime);
    });
    $('#endTime').datepicker(dataPickerOption).on('changeDate',function(e){
        var endTime = e.date;
        $('#startTime').datepicker('setEndDate',endTime);
    })
});

function initParam(){
    var tripInfo = [];
    $.each($('.timeline-container'),function (index,iTrip) {
        var tripContent = {dayNo:index+1,};
        var activities =[];
        $.each($(iTrip).find('.transparent'),function (acIndex,iActivity) {
            activities.push({
                sortNo : acIndex+1,
                title : $(iActivity).find('.activity-title').text(),
                content : $(iActivity).find('.activity-content').html()
            });
        });
        tripContent.activities = activities;
        tripInfo.push(tripContent);
    });
    return tripInfo;
}